package com.qf.openapi.web.master.interceptor;

import com.qf.openapi.web.master.entity.User;
import com.qf.openapi.web.master.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Optional;


@Slf4j
public class LoginStatusInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        
        log.debug("拦截器所拦截的url:{}", request.getRequestURI());
        
        
        // 判断用户是否登录过
        final HttpSession session = request.getSession();
        final User user = (User) session.getAttribute(Constants.USER_SESSION_KEY);
        if (Optional.ofNullable(user).isPresent()){
            log.debug("session已经有user对象了，登陆过，放行！");
            return true;
        }
        // 如果没有登录，则重定向到登录页面去
        // 当访问的页面路径为http://localhost:8080/view/user.html
        // 下面的代码会重定向到如下路径 http://localhost:8080/view/login.html
        log.debug("没有登陆过，重定向到登录页面");
        
        response.sendRedirect("/login.html");
        
        return false;
    }
}
